package com.example.goband.api;

import com.example.goband.common.AppVariable;
import com.example.goband.game.FightResponse;
import com.example.goband.game.OnlineUserManager;
import com.example.goband.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.util.Map;


@Component
public class FightApi extends TextWebSocketHandler {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate_int;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private OnlineUserManager onlineUserManager;

    @Override
    public void afterConnectionEstablished (WebSocketSession session) throws Exception {
        User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
//        String userid = user.getUserId().toString();
        onlineUserManager.enterGameRoom_new(user.getUserId(), session);
        //将所有用户名返回给前端

    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //获取userid、roomid、用户的选项
        User user = (User) session.getAttributes().get(AppVariable.USER_SESSION_KEY);
        String userid = user.getUserId().toString();
        String roomid = session.getAttributes().get("roomid").toString();
        int hand = Integer.parseInt(message.getPayload());
        //判断是不是房主,然后判断另一个玩家是否已提交
        Map<Object, Object> room = redisTemplate.opsForHash().entries(roomid);
        String owner = room.get("owner").toString();
        String guest = room.get("guest").toString();
        int owner_hand = Integer.parseInt(room.get("owner_hand").toString());
        int guest_hand = Integer.parseInt(room.get("guest_hand").toString());
        FightResponse fg = new FightResponse();
        if (owner.equals(userid)){
            redisTemplate_int.opsForHash().put(roomid,"owner_hand",hand);
            if (guest.equals("0") || guest_hand == 0){
//                return;
            }else {
//                fg.setMessage("ok");
//                fg.setHand(Integer.parseInt(redisTemplate_int.opsForHash().get(roomid,"guest").toString()));
//                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(guest_hand)));
                Map<Object, Object> room_new = redisTemplate.opsForHash().entries(roomid);
//                String guest_new = room_new.get("guest").toString();
                String owner_hand_new = room_new.get("owner_hand").toString();
                WebSocketSession session_b = onlineUserManager.getFromGameRoom(Integer.parseInt(guest));
                session_b.sendMessage(new TextMessage(objectMapper.writeValueAsString(Integer.parseInt(owner_hand_new))));
                //TODO将结果写到mysql的用户表中


                //TODO判断谁获胜，并将得分写入redis中----这是为了三局两胜做准备
                //TODO暂时用清空双方手势进入下一局
                redisTemplate_int.opsForHash().put(roomid, "guest_hand", 0);
                redisTemplate_int.opsForHash().put(roomid, "owner_hand", 0);
            }
        }else {
            redisTemplate_int.opsForHash().put(roomid,"guest_hand",hand);
            if (owner.equals("0") || owner_hand == 0){
//                return;
            }else {
//                fg.setMessage("ok");
//                fg.setHand(Integer.parseInt(redisTemplate_int.opsForHash().get(roomid,"owner").toString()));
//                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(resp)));
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(owner_hand)));
                Map<Object, Object> room_new = redisTemplate.opsForHash().entries(roomid);
//                String owner_new = room_new.get("owner").toString();
                String guest_hand_new = room_new.get("guest_hand").toString();
                WebSocketSession session_b = onlineUserManager.getFromGameRoom(Integer.parseInt(owner));
                session_b.sendMessage(new TextMessage(objectMapper.writeValueAsString(Integer.parseInt(guest_hand_new))));
                //TODO暂时用清空双方手势进入下一局
                redisTemplate_int.opsForHash().put(roomid, "guest_hand", 0);
                redisTemplate_int.opsForHash().put(roomid, "owner_hand", 0);
            }
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//房主退出后销毁房间
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }
}
